'use strict';
const {
	verifyToken
} = require("../../../uniCloud-aliyun/cloudfunctions/common/wx-common");
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	const db = uniCloud.database();
	const payload = event.token ? verifyToken(event.token) : null;
	//订单编号
	async function generateOrderNumber() {
		const maxOrderNoResult = await db.collection('orders').orderBy('order_no', 'desc').limit(1).get();
		const lastOrderNo = maxOrderNoResult.data.length > 0 ? maxOrderNoResult.data[0].order_no : 0;
		const newOrderNo = lastOrderNo + 1;
		return newOrderNo;
	}
	const order_no = await generateOrderNumber();
	const status = event.status; // 订单状态，例如 "进行中"
	const cartAmount = event.cartAmount; // 订单合计金额
	const address = event.address; // 订单地址
	const productImages = event.productImages; // 订单中的商品图片
	const created_at = event.created_at // 获取当前时间
	const no = Date.now();
	const userId=event.userId
	const order = {
		no,
		status,
		cartAmount,
		address,
		productImages,
		created_at,
		order_no,
		userId
	};

	try {
		// 插入订单数据到云数据库
		const res = await db.collection('orders').add(order);
		return {
			code: 0,
			message: '订单创建成功',
			order: res.data || {}
		};
	} catch (err) {
		return {
			code: -1,
			message: '订单创建失败',
			error: err
		};
	}
	//返回数据给客户端
	return res;
};